/*
 * Copyright © 2012 by PropSage Pte Ltd. 
 * All Rights Reserved.
 * licensing@propsage.com
 * http://www.propsage.com/terms.html
 * 
 * @author Poh Nean
 */
propsage.namespace("propsage.brochure");


/**
 * Factsheet Widget Class
 */
(function($){
	propsage.brochure.Widget = Class.extend({
		type: 'Widget',
		template: false,
		selectable: false,
		resizable: false,
		resizableOptions: {},
		draggable: false,
		draggableOptions: {},
		rotatable: false,
		isSelected: false,
		defaults: {
			page: 1,
			width: 150,
			height: 100,
			x: 100,
			y: 100,
			matrix: [1,0,0,1]
		},
		setup: function() {},
		init: function(data) {
			if (typeof propsage.brochure.widgets[this.type].__setupDone === 'undefined' || propsage.brochure.widgets[this.type].__setupDone === false) {
				this.setup();
				propsage.brochure.widgets[this.type].__setupDone = true;
			}
			
			// Initialize variables
			if (typeof propsage.brochure.Widget.__uniqueid === 'undefined') {
				propsage.brochure.Widget.__uniqueid = 1;
			}
			
			if (data.id) {
				this.id = parseInt(data.id);
				if (this.id > propsage.brochure.Widget.__uniqueid) {
					propsage.brochure.Widget.__uniqueid = this.id + 1;
				}
			} else {
				this.id = this.uniqueId();
			}			
			
			// apply defaults
			this.options = $.extend({}, this.defaults, data.options);
			
			this.create();
		},
		create: function() {
			var self = this, o = this.options;
			
			// Create element
			var $handle, $handleButton;
		
			// create container
			this.container = $('<div />')
			.addClass('widget')
			.addClass('widget-' + this.type)
			.attr('id', 'widget-' + this.id)
			.attr('widget-id', this.id);
			
			// create handle and bind events
			$handle = $('<div />');
			$handle.addClass('widget-handle');
			
			if (this.handleActions) {
				$.each(this.handleActions, function(handleActionName, handleAction) {
					$handleButton = $('<div />')
					.attr('title', handleAction.title)
					.addClass('widget-handle-action')
					.addClass('widget-handle-action-' + handleActionName);
					
					if (handleAction.click != null && $.isFunction(handleAction.click)) {
						$handleButton.on('click', $.proxy(handleAction.click, self));
					}
					$handleButton.appendTo($handle);
				});
			}
			$handle.appendTo(this.container);
			
			this.handle = $handle;
			
			// create widget
			this.widget = $(this.template);
			this.widget.html(this.getContents());			
			this.widget.appendTo(this.container);
			
			this.container
			.width(o.width)
			.height(o.height)
			.data("widget", this);
			
			// rotate widget
			if (o.matrix) {
				var matrix = 'matrix('+ o.matrix[0] +', '+ o.matrix[1] +', '+ o.matrix[2] +', '+ o.matrix[3] +', 0, 0)',
				ie_matrix = "progid:DXImageTransform.Microsoft.Matrix(M11='"+o.matrix[0]+"', M12='"+o.matrix[1]+"', M21='"+o.matrix[2]+"', M22='"+o.matrix[3]+"', sizingMethod='auto expand')";        	
        	  
				this.container.css({
					'-moz-transform'   : matrix,
					'-o-transform'     : matrix,
					'-webkit-transform': matrix,
					'-ms-transform'    : matrix,
					'transform'        : matrix,
					'filter'           : ie_matrix,
					'-ms-filter'       : '"' + ie_matrix + '"'
				});
        	
			// IE Fix
			//			if($.browser.msie) {
			//				var	coef    = this.dims.w / this.dims.h,
			//				_height = this.element.parent().parent().height()
			//				this._width  = coef * _height,
			//				this._top    = (this.dims.h - _height) / 2,
			//				this._left   = (this.dims.w - this._width) / 2;
			//	        	
			//				this.element.parent().parent().css({
			//					'width'      : this._width
			//				});
			//	        	
			//				this.element.parent().css({
			//					'left': this._left,
			//					'top' : this._top
			//				});
			//			}
			}
			
			// position widget
			this.container.css({
				'position': 'absolute',
				'left': o.x + 'px',
				'top': o.y + 'px'
			});
			
			// init event handlers
			this.bindEvents();
		},
		getContents: function() {
			return '';
		},
		destroy: function() {
			this.unbindEvents();
			
			this.container.remove();
		},
		bindEvents: function() {
			var self = this;
			var $widget = this.widget;
			
			if (this.selectable == true) {				
				this.container.addClass('widget-selectable');
			}
			
			if (this.resizable == true) {
				this.container.addClass('widget-resizable');
			}
						
			if (this.draggable == true) {
				this.container.addClass('widget-draggable');
			}
			
			if (this.rotatable == true) {
				this.container.addClass('widget-rotatable');
			}
						
			if (this.events != null) {
				$.each(this.events, function(eventType, eventHandler) {
					$widget.bind(eventType, $.proxy(eventHandler, self));
				});
			}
		},
		unbindEvents: function() {
			var $widget = this.widget;
			
			if (this.events != null) {
				$.each(this.events, function(eventType, eventHandler) {
					$widget.unbind(eventType);
				});
			}
		},
		/**
		 * Programatically trigger selection of current widget
		 */
		triggerSelect: function(e) {
			var selectableContainer = this.container.closest('.ui-selectable');
			
			this.container.addClass('ui-selected');
			$('.ui-selected', selectableContainer).not(this.container).each(function(){
				$(this)
				.removeClass('ui-selected')
				.data('widget')
				.triggerUnselect(e);
			});
			
			this.onSelected(e);
		},
		/**
		 * Programatically trigger unselection of current widget
		 */
		triggerUnselect: function(e) {
			this.onUnselected(e);
		},
		onResize: function(e) {
			this.options.width = this.container.width();
			this.options.height = this.container.height();
		},
		onSelecting: function(e, ui) {},
		onUnselecting: function(e, ui) {},
		onSelected: function(e, ui) {
			var self = this, o = this.options;
			this.isSelected = true;
			
			// activate draggable
			if (this.draggable == true) {
				this.container.draggable({
					snap: '#pages .body .content, .widget',
					handle: '.widget-handle',
					containment: 'parent'
				});
			}
			
			// activate resizable	
			if (this.resizable == true) {		
				if (this.resizableOptions && $.isFunction(this.onResize)) {
					this.resizableOptions.resize = $.proxy(this.onResize, self);
				}
			
				this.resizableOptions.handles = 'all';
				this.resizableOptions.snap = '#pages .body .content, .widget';
				this.resizableOptions.snapMode = 'both';
				this.container.resizable(this.resizableOptions);
			}
			
			// activate rotatable
			if (this.rotatable == true) {
				this.container.rotatable({
					matrix: o.matrix
				});
			}
		},
		onUnselected: function(e, ui) {		
			this.isSelected = false;
			
			this.container.resizable('destroy');
			this.container.draggable('destroy');
			this.container.rotatable('destroy');
		},
		uniqueId: function() {		
			return propsage.brochure.Widget.__uniqueid++;
		}
	});
})(jQuery);
